<template>
  <view class="container">
    <!-- Header with action buttons -->
    <view class="header">
      <uni-search-bar v-model="searchTerm" @confirm="filterItems" placeholder="搜索进货记录" class="search-bar"></uni-search-bar>
      <uni-button type="primary" size="mini" @click="openAddPopup">新增进货</uni-button>
    </view>

    <!-- Stock in list table -->
    <uni-table :border="true">
      <uni-tr>
        <uni-th align="center">商品编号</uni-th>
        <uni-th align="center">商品名称</uni-th>
        <uni-th align="center">进货数量</uni-th>
        <uni-th align="center">进货单价</uni-th>
        <uni-th align="center">总金额</uni-th>
        <uni-th align="center">供货商</uni-th>
        <uni-th align="center">规格</uni-th>
        <uni-th align="center">进货时间</uni-th>
        <uni-th align="center">过期时间</uni-th>
        <uni-th align="center">预警天数</uni-th>
        <uni-th align="center">操作</uni-th>
      </uni-tr>
      <uni-tr v-for="item in filteredItems" :key="item.id">
        <uni-td align="center">{{ item.product_code }}</uni-td>
        <uni-td align="center">{{ item.product_name}}</uni-td>
        <uni-td align="center">{{ item.quantity }}</uni-td>
        <uni-td align="center">{{ item.price }}</uni-td>
        <uni-td align="center">{{ item.total_amount }}</uni-td>
        <uni-td align="center">{{ getSupplierById(item.supplier_id).name }}</uni-td>
        <uni-td align="center">{{ item.spec_name }}</uni-td>
        <uni-td align="center">{{ item.created_at }}</uni-td>
        <uni-td align="center">{{ item.expiration_time }}</uni-td>
        <uni-td align="center">{{ item.time_warning }}</uni-td>
        <uni-td align="center">
          <uni-button type="primary" size="mini" @click="openEditPopup(item)">编辑</uni-button>
          <uni-button type="default" size="mini" @click="deleteItem(item.id)">删除</uni-button>
        </uni-td>
      </uni-tr>
    </uni-table>
    
    <!-- 使用 uni-pagination 分页组件 -->
    <view style="margin-top: 20px;">
      <uni-pagination 
        :current="pagination.currentPage" 
        :total="pagination.totalRecords" 
        :pageSize="pagination.pageSize"
        @change="handlePageChange" 
      />
    </view>

    <!-- Popup for adding new stock in -->
    <uni-popup ref="addPopup" type="center">
      <view class="popup-container">
        <h3>新增进货</h3>
        <view class="form-row">
          <label>选择商品：</label>
          <picker mode="selector" :range="productPickerList2" range-key="product_name" @change="updateProductId" class="input-field">
            <view>{{ getProductById2(newItem.product_id).product_name || '请选择商品' }}</view>
          </picker>
        </view>
        <view class="form-row">
          <label>进货数量：</label>
          <input v-model="newItem.quantity" class="input-field" type="number" />
        </view>
         <view class="form-row">
          <label>规格：</label>
          <picker mode="selector" :range="specPickerList" range-key="spec_name" @change="updateSpecId" class="input-field">
            <view>{{ getSpecById(newItem.spec_id).spec_name || '请选择规格' }}</view>
          </picker>
        </view>
        <view class="form-row">
          <label>进货单价：</label>
          <input v-model="newItem.price" class="input-field" type="number" />
        </view>
        <view class="form-row">
          <label>总金额：</label>
          <input v-model="newItem.total_amount" class="input-field" type="number" readonly />
        </view>
        <view class="form-row">
          <label>供货商：</label>
          <picker mode="selector" :range="supplierPickerList" range-key="name" @change="updateSupplierId" class="input-field">
            <view>{{ getSupplierById(newItem.supplier_id).name || '请选择供货商' }}</view>
          </picker>
        </view>
        <view class="form-row">
          <label>预警天数：</label>
          <input v-model="newItem.time_warning" class="input-field" type="number" />
        </view>
        <view class="form-row">
          <label>过期时间：</label>
          <picker mode="date" :value="newItem.expiration_time" @change="updateExpirationDate('newItem', $event)">
            <view class="input-field">{{ newItem.expiration_time || '选择日期' }}</view>
          </picker>
        </view>
        <view class="button-group">
          <uni-button type="primary" size="small" @click="addNewStockIn">添加</uni-button>
          <uni-button type="default" size="small" @click="closePopup">取消</uni-button>
        </view>
      </view>
    </uni-popup>

    <!-- Popup for editing stock in -->
    <uni-popup ref="editPopup" type="center">
      <view class="popup-container">
        <h3>编辑进货</h3>
        <view class="form-row">
          <label>选择商品：</label>
          <picker mode="selector" :range="productPickerList2" range-key="product_name" @change="updateEditProductId" class="input-field">
            <view>{{ getProductById2(editItem.product_id).product_name || '请选择商品' }}</view>
          </picker>
        </view>
        <view class="form-row">
          <label>进货数量：</label>
          <input v-model="editItem.quantity" class="input-field" type="number" />
        </view>
        <view class="form-row">
              <label>规格：</label>
              <picker mode="selector" :range="specPickerList" range-key="spec_name" @change="updateEditSpecId" class="input-field"  :value="getDefaultSpecIndex()">
                <view>{{ getSpecById(editItem.spec_id).spec_name || '请选择规格' }}</view>
              </picker>
            </view>
        <view class="form-row">
          <label>进货单价：</label>
          <input v-model="editItem.price" class="input-field" type="number" />
        </view>
        <view class="form-row">
          <label>总金额：</label>
          <input v-model="editItem.total_amount" class="input-field" type="number" readonly />
        </view>
        <view class="form-row">
          <label>供货商：</label>
          <picker mode="selector" :range="supplierPickerList" range-key="name" @change="updateEditSupplierId" class="input-field">
            <view>{{ getSupplierById(editItem.supplier_id).name || '请选择供货商' }}</view>
          </picker>
        </view>
        <view class="form-row">
          <label>预警天数：</label>
          <input v-model="editItem.time_warning" class="input-field" type="number" />
        </view>
        <view class="form-row">
          <label>过期时间：</label>
          <picker mode="date" :value="editItem.expiration_time" @change="updateExpirationDate('editItem', $event)">
            <view class="input-field">{{ editItem.expiration_time || '选择日期' }}</view>
          </picker>
        </view>
        <view class="button-group">
          <uni-button type="primary" size="small" @click="saveEditStockIn">保存</uni-button>
          <uni-button type="default" size="small" @click="closeEditPopup">取消</uni-button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchTerm: '',
      items: [], // 从后端获取的进货记录数据
      filteredItems: [],
      newItem: { product_id: '', quantity: 0, price: 0, total_amount: 0, supplier_id: '', spec_id: '', time_warning: 10, expiration_time: '' },
      editItem: { id: '', product_id: '', quantity: 0, price: 0, total_amount: 0, supplier_id: '', spec_id: '', time_warning: 0, expiration_time: '' },
      products: [], // 商品列表
      products2: [], // 商品列表2
      suppliers: [], // 供应商列表
      specs: [], // 规格列表
      productPickerList: [], // 商品选择列表
      productPickerList2: [], // 商品选择列表2
      supplierPickerList: [], // 供应商选择列表
      specPickerList: [], // 规格选择列表
      mainAccountId: '',
      userInfo: {}, // 用户信息
      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10,
        totalRecords: 0
      }
    };
  },
  computed: {
    // 计算总页数
    totalPages() {
      return Math.ceil(this.pagination.totalRecords / this.pagination.pageSize);
    }
  },
  watch: {
    'newItem.quantity'(val) {
      this.calculateTotalAmount();
    },
    'newItem.price'(val) {
      this.calculateTotalAmount();
    },
    'editItem.quantity'(val) {
      this.calculateEditTotalAmount();
    },
    'editItem.price'(val) {
      this.calculateEditTotalAmount();
    }
  },
  methods: {
    async fetchItems() {
      try {
        const res = await this.$myRuquest({
          url: '/index/plugin.stock/getStockIn',
          method: 'GET',
          data: {
            main_account_id: this.mainAccountId,
            page: this.pagination.currentPage,  // 添加页码参数
            pageSize: this.pagination.pageSize  // 添加每页大小参数
          }
        });
        
        if (res.data.code === 200) {
          // 确保数据是数组，如果不是则转换为数组
          this.items = Array.isArray(res.data.data.items) ? res.data.data.items : [res.data.data.items];
          // console.log(this.items)
          this.filteredItems = [...this.items]; // 现在可以安全使用扩展运算符
          // 更新分页信息
          this.pagination.totalRecords = res.data.data.totalRecords || 0;
          // 确保当前页不超过总页数
          if (this.pagination.currentPage > this.totalPages && this.totalPages > 0) {
            this.pagination.currentPage = this.totalPages;
            this.fetchItems(); // 重新获取数据
          }
        } else {
          uni.showToast({
            title: res.data.message || '获取数据失败',
            duration: 2000,
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取进货记录失败:', error);
        uni.showToast({
          title: '获取数据失败',
          duration: 2000,
          icon: 'none'
        });
      }
    },
    
    // 处理分页变化
    handlePageChange(e) {
      this.pagination.currentPage = e.current;
      this.fetchItems();
    },
    async fetchProducts() {
      // 从后端获取商品列表
      const res = await this.$myRuquest({
        url: '/index/plugin.stock/getProducts',
        method: 'GET',
        data: {
          main_account_id: this.mainAccountId,
        }
      });
      if (res.data.code === 200) {
        this.products = res.data.data;
        this.productPickerList = this.products.map(product => ({
          value: product.id,
          product_name: product.product_name
        }));
      } else {
        uni.showToast({
          title: res.data.message,
          duration: 2000,
          icon: 'none'
        });
      }
    },
    async fetchProducts2() {
      // 从后端获取商品列表2
      const res = await this.$myRuquest({
        url: '/index/plugin.stock/get_x_products',
        method: 'GET',
        data: {
          user_id: this.mainAccountId,
        }
      });
      if (res.data.code === 200) {
		  console.log(res.data.data);
        this.products2 = res.data.data;
        this.productPickerList2 = this.products2.map(product => ({
          value: product.id,
          product_name: product.product_name
        }));
      } else {
        uni.showToast({
          title: res.data.message,
          duration: 2000,
          icon: 'none'
        });
      }
    },
    async fetchSuppliers() {
      // 从后端获取供应商列表
      const res = await this.$myRuquest({
        url: '/index/plugin.stock/getSuppliers',
        method: 'GET',
        data: {
          main_account_id: this.mainAccountId,
        }
      });
      if (res.data.code === 200) {
        this.suppliers = res.data.data;
        this.supplierPickerList = this.suppliers.map(supplier => ({
          value: supplier.id,
          name: supplier.name
        }));
      } else {
        uni.showToast({
          title: res.data.message,
          duration: 2000,
          icon: 'none'
        });
      }
    },
    async fetchSpecs() {
      // 从后端获取规格列表
      const res = await this.$myRuquest({
        url: '/index/plugin.stock/getAllSpecs',
        method: 'GET',
        data: {
          main_account_id: this.mainAccountId,
        }
      });
      if (res.data.code === 200) {
        this.specs = res.data.data;
        this.specPickerList = this.specs.map(spec => ({
          value: spec.id,
          spec_name: spec.spec_name
        }));
        // 自动选择第一个规格作为默认值
        if (this.specPickerList.length > 0) {
          this.newItem.spec_id = this.specPickerList[0].value;
        }
      } else {
        uni.showToast({
          title: res.data.message,
          duration: 2000,
          icon: 'none'
        });
      }
    },
    filterItems() {
      if (this.searchTerm) {
        this.filteredItems = this.items.filter(item =>
          item.product_name.includes(this.searchTerm) ||
          item.product_id.includes(this.searchTerm)
        );
      } else {
        this.filteredItems = this.items;
      }
    },
    openAddPopup() {
      this.newItem = { product_id: '', quantity: 0, price: 0, total_amount: 0, supplier_id: '',
      spec_id: this.specPickerList.length > 0 ? this.specPickerList[0].value : '', // 默认选择第一个规格
      time_warning: 10, expiration_time: '' };
      this.fetchProducts2(); // 获取商品列表2
      this.fetchSpecs(); // 获取规格列表
      this.$refs.addPopup.open();
    },
    getDefaultSpecIndex() {
      if (!this.newItem.spec_id || this.specPickerList.length === 0) return 0;
      const index = this.specPickerList.findIndex(item => item.value === this.newItem.spec_id);
      return index >= 0 ? index : 0;
    },
    closePopup() {
      this.$refs.addPopup.close();
    },
    openEditPopup(item) {
      this.editItem = { ...item };
      this.fetchSpecs(); // 获取规格列表
      this.$refs.editPopup.open();
    },
    closeEditPopup() {
      this.$refs.editPopup.close();
    },
    calculateTotalAmount() {
      this.newItem.total_amount = (this.newItem.quantity * this.newItem.price).toFixed(2);
    },
    calculateEditTotalAmount() {
      this.editItem.total_amount = (this.editItem.quantity * this.editItem.price).toFixed(2);
    },
    async addNewStockIn() {
      // 添加新进货记录
      console.log(this.newItem); // 调试输出
      const res = await this.$myRuquest({
        url: '/index/plugin.stock/saveStockIn',
        method: 'POST',
        data: {
          main_account_id: this.mainAccountId,
          shop_id: 0,
          ...this.newItem
        }
      });
      if (res.data.code === 200) {
        uni.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 2000
        });
        this.fetchItems();
        this.closePopup();
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
      }
    },
    async saveEditStockIn() {
      // 保存编辑的进货记录
      console.log(this.editItem); // 调试输出
      const res = await this.$myRuquest({
        url: '/index/plugin.stock/updateStockIn',
        method: 'POST',
        data: {
          main_account_id: this.mainAccountId,
          shop_id: 0,
          ...this.editItem
        }
      });
      if (res.data.code === 200) {
        uni.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        });
        this.fetchItems();
        this.closeEditPopup();
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
      }
    },
    async deleteItem(id) {
      // 删除进货记录
      const res = await this.$myRuquest({
        url: '/index/plugin.stock/deleteStockIn',
        method: 'POST',
        data: {
          main_account_id: this.mainAccountId,
          id: id
        }
      });
      if (res.data.code === 200) {
        uni.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        });
        this.fetchItems();
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
      }
    },
    updateExpirationDate(type, event) {
      this[type].expiration_time = event.detail.value;
    },
    getProductById(id) {
      console.log(id)
      return this.products.find(product => product.id === id) || {};
    },
    getProductById2(id) {
      return this.products2.find(product => product.id === id) || {};
    },
    getSupplierById(id) {
      return this.suppliers.find(supplier => supplier.id === id) || {};
    },
    getSpecById(id) {
      return this.specs.find(spec => spec.id === id) || {};
    },
    updateProductId(e) {
      this.newItem.product_id = this.productPickerList2[e.detail.value].value;
      console.log(this.newItem.product_id); // 调试输出
    },
    updateSupplierId(e) {
      this.newItem.supplier_id = this.supplierPickerList[e.detail.value].value;
    },
    updateSpecId(e) {
      this.newItem.spec_id = this.specPickerList[e.detail.value].value;
    },
    updateEditProductId(e) {
      this.editItem.product_id = this.productPickerList2[e.detail.value].value;
      console.log(this.editItem.product_id); // 调试输出
    },
    updateEditSupplierId(e) {
      this.editItem.supplier_id = this.supplierPickerList[e.detail.value].value;
    },
    updateEditSpecId(e) {
      this.editItem.spec_id = this.specPickerList[e.detail.value].value;
    },
    checkLoginStatus() {
      const token = uni.getStorageSync('token');
      if (token) {
        this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
        this.mainAccountId = this.userInfo.user_id;
      } else {
        this.userInfo = {};
        this.$router.push('/pages/login/login');
      }
    }
  },
  mounted() {
    this.checkLoginStatus();
    this.fetchItems();
    this.fetchProducts();
    this.fetchSuppliers();
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #ecf0f1;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  background-color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
}
.search-bar {
  flex: 1;
  margin-right: 10px;
}
.uni-table {
  width: 100%;
  border-collapse: collapse;
}
.uni-th, .uni-td {
  padding: 10px;
  border: 1px solid #ddd;
}
.uni-th {
  background-color: #f9f9f9;
}
.popup-container {
  width: 80%;
  max-width: 500px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
label {
  width: 80px;
  color: #666;
  margin-right: 10px;
}
.input-field {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}
.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
.uni-button {
  margin-left: 10px;
}
</style>
